<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-09-21
 * Time: 13:46:00
 * Info:
 */

namespace plugin\email\app\controller;

use plugin\email\app\model\PluginOptions;
use plugin\email\app\model\Template;
use plugin\email\api\Email;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use think\facade\Db;

class EmailController
{

    public function index()
    {
        return view('email/index');
    }

    /**
     * 获取设置
     * @return \support\Response|\think\response\Json|null
     */
    public function get()
    {
        $data = PluginOptions::where('name', Email::SETTING_OPTION_NAME)->value('value');
        $data = ! empty($data) ? json_decode($data, true) : [
            'Host'       => 'smtp.qq.com',
            'Username'   => '',
            'Password'   => '',
            'SMTPSecure' => 'ssl',
            'Port'       => 465,
            'From'       => '',
        ];

        return json(['code' => 200, 'data' => $data, 'msg' => 'ok']);
    }

    /**
     * 保存邮件配置
     */
    public function save(Request $request)
    {
        $data   = [
            'Host'       => $request->post('Host'),
            'Username'   => $request->post('Username'),
            'Password'   => $request->post('Password'),
            'SMTPSecure' => $request->post('SMTPSecure'),
            'Port'       => $request->post('Port'),
            'From'       => $request->post('From'),
        ];
        $value  = json_encode($data);
        $name   = Email::SETTING_OPTION_NAME;
        $option = PluginOptions::where('name', $name)->find();
        if ($option) {
            PluginOptions::where(['name' => $name])->data(['value' => $value])->update();
        } else {
            $option        = new PluginOptions();
            $option->name  = $name;
            $option->value = $value;
            $option->save();

            // 默认生成一个验证码邮件模版
            $templateName = 'captcha';
            if (empty(Template::findData($templateName))) {
                dump("生成新模板");
                Template::saveData($templateName, $data['From'], '验证码',
                    '验证码为 {code} 。如您未发送过该邮件，请忽略。');
            }
        }

        return json(['code' => 200, 'msg' => 'ok']);
    }

    public function test(Request $request)
    {
        $from    = $request->post('From');
        $to      = $request->post('To');
        $subject = $request->post('Subject');
        $content = $request->post('Content');

        Email::Send($from, $to, $subject, $content);

        return json(['code' => 200, 'msg' => '发送成功']);
    }

    /**
     * 获取模板
     */
    public function selectTemplate(Request $request)
    {
        $params = $request->get();
        if ( ! empty($params['type']) && $params['type'] == 'test') {
            //发送邮件获取名称
            $data = Db::name('plugin_email_template')->select()->toArray();
        } else {
            $limit = $params['limit'];
            $first = ($params['page'] - 1) * $limit;
            $data  = Db::name('plugin_email_template')->where(function ($query) use ($params) {
                if ( ! empty($params['name'])) {
                    $query->whereLike('name', '%'.$params['name'].'%');
                }
            })->limit($first, $limit)->select()->toArray();
        }

        return json(['code' => 0, 'data' => $data, 'msg' => 'ok']);
    }

    /**
     * 保存设置
     * @return \support\Response|\think\response\Json|null
     */
    public function insertTemplate(Request $request)
    {
        if ($request->isPost()) {
            $params = $request->post();
            if (empty($params['name'])) {
                return json(['code' => 0, 'msg' => '模板名称不能为空']);
            }
            $time                  = time();
            $params['create_time'] = $time;
            $params['update_time'] = $time;
            Db::name('plugin_email_template')->insert($params);

            return json(['code' => 200, 'msg' => 'ok']);
        }

        return view('email/insert');
    }

    public function updateTemplate(Request $request)
    {
        if ($request->isPost()) {
            $params                = $request->post();
            $params['update_time'] = time();
            Db::name('plugin_email_template')->where(['id' => $params['id']])->data($params)->update();

            return json(['code' => 200, 'msg' => 'ok']);
        }
        $id   = $request->get('id');
        $data = Db::name('plugin_email_template')->find($id);
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '模版不存在']);
        }

        return view('email/update', ['data' => $data]);
    }

    /**
     * 删除
     *
     * @param Request $request
     *
     * @return Response
     */
    public function deleteTemplate(Request $request)
    {
        $ids = (array)$request->post('id');
        Template::deleteTemplate($ids);

        return json(['code' => 200, 'msg' => 'ok']);
    }

    public function testTemplate(Request $request)
    {
        if ($request->isPost()) {
            $name = $request->post('name');
            $to   = $request->post('to');
            $data = $request->post('data');
            $data = $data ? json_decode(htmlspecialchars_decode($data), true) : [];

            Email::sendByTemplate($to, $name, $data);

            return json(['code' => 200, 'msg' => 'ok']);
        }

        return view('email/test_send');
    }

}
